<template>
  <el-form :model="userform" :rules="rules" ref="userform" label-position="left" label-width="0px"
           class="demo-ruleForm login-container">
    <h3 class="title">系统登录</h3>
    <el-form-item prop="username">
      <el-input type="text" v-model="userform.username" auto-complete="off" placeholder="账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="userform.password" auto-complete="off" placeholder="密码"></el-input>
    </el-form-item>
    <el-checkbox v-model="checked" checked class="remember">记住密码</el-checkbox>
    <el-form-item style="width:100%;">
      <el-button type="primary" style="width:100%;" @click.native.prevent="handleSubmit2"
                 :loading="logining">登录</el-button>
      <!--<el-button type="primary" style="width:45%;" @click.native.prevent="register">公司入驻</el-button>-->
    </el-form-item>
  </el-form>
</template>

<script>
import { requestLogin } from '../api/api';

//import NProgress from 'nprogress'
export default {
  data() {
    return {
      logining: false,
      userform: {
        username: '卓子良',
        password: '123',
        // 登录的类型 为0  表示在后台登录,一般在使用在登录首页
        type: 0
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          //{ validator: validaePass }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          //{ validator: validaePass2 }
        ]
      },
      checked: true
    };
  },
  methods: {
    // 动态添加路由函数
    initIndexRouters() {
      if (!localStorage.menus) {
        return;
      }
      //防止重复配置路由：4就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
      if (this.$router.options.routes.length > 4) {
        return;
      }
      let menus = localStorage.getItem('menus');
      menus = JSON.parse(menus);
      let tempRouters = [];
      menus.forEach(menu => {
        let indexRouter = {
          path: '/',
          iconCls: menu.icon,
          name: menu.name,
          component: resolve => require(['@/views/Home'], resolve),
          children: []
        }
        menu.children.forEach(cMenu => {
          let cr = {
            path: cMenu.url,
            name: cMenu.name,
            component: resolve => require(['@/views/' + cMenu.component], resolve)
          }
          indexRouter.children.push(cr)
        })
        tempRouters.push(indexRouter)
        this.$router.options.routes.push(indexRouter)
      })
      //动态路由配置
      this.$router.addRoutes(tempRouters);
    },
    register() {
      //跳转到公司入驻界面
      this.$router.push({ path: '/register' });
    },
    handleReset2() {
      this.$refs.userform.resetFields();
    },
    //处理登录请求
    handleSubmit2(ev) {
      //  this.$refs: 找到表单校验通过
      // user: 校验一个ref属性为user的表单
      // validate
      this.$refs.userform.validate((valid) => {
        if (valid) {
          this.logining = true;
          // debugger
          //发请求获取token
          this.$http.post("/login/account", this.userform).then(res => {
            if (res.data.success) {
              var token = res.data.data;
              let jwt = require('jsonwebtoken');

              let resultJwtJson = jwt.decode(token);
              const { payload } = resultJwtJson
              const { user, menus, permissionSns } = payload

              // console.log(user);
              // console.log(menus);
              console.log(JSON.stringify(permissionSns));

              //把token存储起来
              localStorage.setItem("Authorization", token);
              localStorage.setItem("permissionSns", JSON.stringify(permissionSns));
              localStorage.setItem("user", JSON.stringify(user));
              localStorage.setItem("menus", JSON.stringify(menus))

              //根据用户菜单权限，动态展示菜单
              this.initIndexRouters()
              //修改登录成功后跳转到首页
              this.$router.push({ path: '/' });
              this.logining = false;
              return;
            } else {
              this.logining = false;
              this.$message.error(res.data.msg);
            }
          }).catch(error => {
            this.$message.error(error.msg);
            this.logining = false;
            return;
          });


        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}

</script>

<style lang="scss" scoped>
.login-container {
  /*box-shadow: 0 0px 8px 0 rgba(0, 0, 0, 0.06), 0 1px 0px 0 rgba(0, 0, 0, 0.02);*/
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-border-radius: 5px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 350px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;

  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
  }

  .remember {
    margin: 0px 0px 35px 0px;
  }
}
</style>
